<template>
    <div class="chat-container">
      <!-- 聊天记录区域 -->
      <div class="chat-history">      <div
          v-for="(message, index) in chatHistory"
          :key="index"
          :class="['message', message.sender]"
        >
          <div class="message-content">
            <!-- 如果是 AI 的消息，使用打字机效果 -->
            <template v-if="message.sender === 'ai' && message.isTyping">
              <span v-for="(char, charIndex) in message.displayText" :key="charIndex">{{ char 
  }}</span>
            </template>
            <template v-else>
              {{ message.text }}
            </template>
          </div>
        </div>
        <!-- 等待动画 -->
        <div v-if="isLoading" class="thinking-animation">
                <div class="dot"></div>
                <div class="dot"></div>
                <div class="dot"></div>
        </div>
      </div>
      <!-- 用户输入区域 -->
      <div class="input-area">
        <input
          v-model="userInput"
          @keyup.enter="sendMessage"
          placeholder="输入你的问题..."/>
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </template>
  <script>
  export default {
    data() {
      return {
        userInput: '', // 用户输入的问题
        chatHistory: [], // 聊天记录
        isLoading:false //等待动画
      };
    },
    methods: {
      // 发送消息
      async sendMessage() {
        if (this.userInput.trim() === '') return; // 如果输入为空，则不发送
        // 添加用户消息到聊天记录
        this.chatHistory.push({ sender: 'user', text: this.userInput });
        // 清空输入框
        this.userInput = '';     // 显示等待动画
        this.isLoading = true;
        // 发送流式请求
        await this.sendStreamingRequest();
        this.isLoading = false;
        // 保存聊天记录到 localStorage
        this.saveChatHistory();
      },
      // 发送流式请求
      async sendStreamingRequest() {
        const url = 'http://localhost:8888/deepSeek/chat'; // Spring Boot 后端流式 API 地址
        const payload = { question: this.chatHistory[this.chatHistory.length - 1].text };
        try {
          const response = await fetch(url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
          });
          if (!response.ok) {
            throw new Error('请求失败');
          }
          // 添加 AI 消息到聊天记录，并标记为正在输入
          this.chatHistory.push({
            sender: 'ai',
            text: '', // 完整的消息内容
            displayText: '', // 用于打字机效果
            isTyping: true, // 标记为正在输入
          });
          const reader = response.body.getReader();
          const decoder = new TextDecoder('utf-8');
          while (true) {
            const { done, value } = await reader.read();
            if (done) break; // 流结束
            // 解码数据块并逐步显示
            const chunk = decoder.decode(value, { stream: true });
            const lines = chunk.split('\n');
           lines.forEach(line => {
               if (line.startsWith('data:')) {
                   const data = line.replace(/^data:\s*/g, '').trim();
                   if (data === '[DONE]') return;
                   this.chatHistory[this.chatHistory.length - 1].text += data;
                   this.chatHistory[this.chatHistory.length - 1].displayText += data;
               }
           });
          }
          // 标记为输入完成
          this.chatHistory[this.chatHistory.length - 1].isTyping = false;     } catch (error) {
          console.error('请求出错:', error);
          this.chatHistory.push({ sender: 'ai', text: '请求出错，请重试。' });
        }
      },
      // 保存聊天记录到 localStorage
      saveChatHistory() {
        localStorage.setItem('chatHistory', JSON.stringify(this.chatHistory));
      },
      // 从 localStorage 加载聊天记录
      loadChatHistory() {
        const history = localStorage.getItem('chatHistory');
        if (history) {
          this.chatHistory = JSON.parse(history);
        }
      },
    },
    mounted() {
      // 组件加载时，从 localStorage 加载历史记录
      this.loadChatHistory();
    },
  };
  </script>
  <style scoped>
  .chat-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 1px;
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    background-color: gray;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  .chat-history {
    height: 500px;
    overflow-y: auto;
    margin-bottom: 20px;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background-color: #fff;
  }
  .message {
    margin-bottom: 15px;
  }
  .message-content {
    padding: 12px 16px; border-radius: 8px;
    display: inline-block;
    max-width: 80%;
    font-size: 14px;
    line-height: 1.5;
  }
  .user .message-content {
    background-color: #007bff;
    color: white;
    text-align: right;
    margin-left: auto;
  }
  .ai .message-content {
    background-color: #f1f1f1;
    color: #333;
    text-align: left;
  }
  .input-area {
    display: flex;
    gap: 1px;
    height: 50px;
  }
  input {
    flex: 1;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
  }
  button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
  }
  button:hover {
    background-color: #0056b3;
  }
  /* 等待动画 */
  .thinking-animation {
    display: flex;
    justify-content: center;
    align-items: center; padding: 10px;
}
.dot {
  width: 8px;
  height: 8px;
  margin: 0 4px;
  background-color: #007bff;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}
.dot:nth-child(2) {
  animation-delay: 0.2s;
}
.dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes bounce {
  0%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
}
</style>